<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use EloquentFilter\Filterable;
use App\Models\Traits\Admin\ActionButtonTrait;
use Illuminate\Support\Facades\Storage;
use Illuminate\Database\Eloquent\Builder;
use Spatie\Permission\Traits\HasRoles;

class Operator extends Model
{
	use Filterable, ActionButtonTrait, HasRoles;

	protected $table = 'admin_users';

    protected $append = ['actionButton'];
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    
    protected $actions = ['edit', 'resetPassword', 'delete'];

    protected $actionUri = 'operators';

    protected $fillable = [
        'name', 'phone', 'password','type','parent_id','avatar','available','last_ip','state'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 
    ];

    public function manager_machine()
    {
        return $this->hasMany(MachineManager::class, 'manager_id', 'id');
    }

    public function machine()
    {
        return $this->belongsToMany(Machine::class, 'machine_managers', 'manager_id', 'machine_id');
    }

    //父级经销商
    public function merchant()
    {
        return $this->belongsTo(Auth::class, 'parent_id', 'id');
    }

    protected static function boot()
    {
        parent::boot();
        //监听添加事件，写入用户类型
        static::creating(function($model){
            $model->type = 4;
            $model->available = 1;
            $model->parent_id = auth('admin')->user()->id;
            $model->password = encrypt_str('123456');
        });
        static::updating(function($model){
            $model->type = 4;
            $model->available = 1;
            $model->parent_id = auth('admin')->user()->id;
        });
        static::created(function($model){
        	$manager = Auth::find($model->id);
        	$manager->assignRole([8]);
        });
        static::addGlobalScope('type', function (Builder $builder) {
            $builder->where('type', 4);
        });
    }
}
